//
//  UITextView+extension.m
//  BiaoQing
//
//  Created by 张帅 on 15/10/13.
//  Copyright © 2015年 ZhangShuai. All rights reserved.
//

#import "UITextView+extension.h"

@implementation UITextView (extension)


-(NSString *)emoticonText
{
    
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithAttributedString:self.attributedText];
    
    __block NSMutableString *strM  =[[NSMutableString alloc] init];
    __block  EmoticonAttachment * attachment =nil;
    
    
    //OC *stop = YES
    
    [attrText  enumerateAttributesInRange:NSMakeRange(0, attrText.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        
//        EmoticonAttachment * attachment =[[EmoticonAttachment alloc] init];
        
        if (attrs[@"NSAttachment"]) {
            
            attachment=   (EmoticonAttachment*)attrs[@"NSAttachment"];
                           
            NSLog(@"表情图片%@", attachment.chs);
            [strM appendString:attachment.chs];
            
        }else{
            
            NSString  *str = [self.attributedText.string substringWithRange:range];
            
            [strM appendString:str];
            
        }
        
        
    }];
    
    return strM.mutableCopy;

}


-(void)insertEmoticon:(FSEmoticonModel *)emoticon
{
    
    
    if (emoticon.isDeleteButton) {
        [self deleteBackward];
        return;
    }
    if (emoticon.isEmptyButton) {
        return;
    }
    if (emoticon.emoji) {
        
        [self replaceRange:self.selectedTextRange withText:emoticon.emoji];
        return;
    }
    
    
    NSAttributedString * imageText =[EmoticonAttachment emoticonAttributeText:emoticon font:self.font];
    
      // 1> 从 textView 中取出属性文本
    
    
    NSMutableAttributedString *strM =[[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
         // 2> 插入图片文字
    
    [strM replaceCharactersInRange:self.selectedRange withAttributedString:imageText];
    
    // 3> 重新设置 textView 的内容
    // 1) 记录当前光标位置
    
    NSRange range =self.selectedRange;
    
    self.attributedText=strM;
    
    
    self.selectedRange = NSMakeRange(range.location +1, 0);
    
    [self.delegate textViewDidChange:self];
    
    
    
//    
//    NSMutableAttributedString* strA = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
//    
//    NSRange lastRange = self.selectedRange;
//    
//    NSMutableAttributedString* imageText = [EmoticonAttachment emoticonTextWithPngPath:model Font:self.font];
//    
//    [strA replaceCharactersInRange:self.selectedRange withAttributedString:imageText];
//    
//    self.attributedText = strA;
//    
//    self.selectedRange = NSMakeRange(lastRange.location + 1, lastRange.length);
//
//    
    
}

@end
